package cloud.keveri.gateway.config.nacos;

import cloud.keveri.gateway.config.api.ConfigCenterService;
import cloud.keveri.gateway.config.api.listener.RulesChangeSubscriber;
import com.alibaba.nacos.api.config.ConfigService;

import java.util.List;

import static cloud.keveri.gateway.config.nacos.def.Const.GATEWAY_RULE_DATA_ID;

/**
 * <p>
 * 作者：沈自在
 **/
public class NacosConfigCenterService extends BaseNacosCacheSupport implements ConfigCenterService {
    public NacosConfigCenterService(final ConfigService configService,
                                    final String env,
                                    final List<RulesChangeSubscriber> rulesChangeSubscribers) {
        super(configService, env, rulesChangeSubscribers);
        initWatcher();
    }

    /**
     * 开启监听
     */
    public void initWatcher() {
        watcherData(GATEWAY_RULE_DATA_ID, this::updateGatewayRules);
    }

    @Override
    public void close() {
        LISTENERS.forEach((dataId, lss) -> {
            lss.forEach(listener -> getConfigService().removeListener(dataId, getEnv(), listener));
            lss.clear();
        });
        LISTENERS.clear();
    }
}
